Warning: mkdir(): No space left on device in /var/www/tg-me/post.php on line 37

Warning: file_put_contents(aCache/aDaily/post/sqlhub/--): Failed to open stream: No such file or directory in /var/www/tg-me/post.php on line 50
Data Science. SQL hub | Telegram Webview: sqlhub/1868 -
Telegram Group & Telegram Channel
👣 Небольшой пример как копировать данные между базами данных используя `go`, `pgx`, и `copy`

Предположим что у нас есть два коннекта к базе (одной или нескольким, это не важно). Далее используя io.Pipe() создаём Reader и Writer, и используя CopyTo() и CopyFrom() переносим данные.

r, w := io.Pipe()

doneChan := make(chan struct{}, 1)

go func() {
defer close(doneChan)

_, err := db1.PgConn().CopyTo(ctx, w, `copy table1 to stdin binary`)
if err != nil {
slog.Error("error", "error", err)
return
}
_ = w.Close()
doneChan <- struct{}{}
}()

_, err = db2.PgConn().CopyFrom(ctx, r, `copy table1 from stdout binary`)
_ = r.Close()

select {
case <-doneChan:
case <-ctx.Done():
}


Вся прелесть тут в том что используем наиболее быстрый способ с точки зрения PostgreSQL.

Используя `copy (select * from where ... order by ... limit ...) to stdout `можем регулировать нагрузку на чтение, следить за прогрессом и управлять копированием данных.

В качестве Reader может выступать что угодно, хоть файл csv, хоть другая СУБД, но тогда данные придётся дополнительно конвертировать в формат понимаемый PostgreSQL - csv или tsv, и использовать copy ... from stdin (format csv).

Нюанс: copy ... from stdin binary , binary обязывает использовать одинаковые типы данных, нельзя будет integer колонку перенести в колонку smallint, если такое требуется, то параметр binary надо опустить.

Весь код тут. И ещё немного кода для вдохновения.

@sqlhub
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/sqlhub/1868
Create:
Last Update:

👣 Небольшой пример как копировать данные между базами данных используя `go`, `pgx`, и `copy`

Предположим что у нас есть два коннекта к базе (одной или нескольким, это не важно). Далее используя io.Pipe() создаём Reader и Writer, и используя CopyTo() и CopyFrom() переносим данные.


r, w := io.Pipe()

doneChan := make(chan struct{}, 1)

go func() {
defer close(doneChan)

_, err := db1.PgConn().CopyTo(ctx, w, `copy table1 to stdin binary`)
if err != nil {
slog.Error("error", "error", err)
return
}
_ = w.Close()
doneChan <- struct{}{}
}()

_, err = db2.PgConn().CopyFrom(ctx, r, `copy table1 from stdout binary`)
_ = r.Close()

select {
case <-doneChan:
case <-ctx.Done():
}


Вся прелесть тут в том что используем наиболее быстрый способ с точки зрения PostgreSQL.

Используя `copy (select * from where ... order by ... limit ...) to stdout `можем регулировать нагрузку на чтение, следить за прогрессом и управлять копированием данных.

В качестве Reader может выступать что угодно, хоть файл csv, хоть другая СУБД, но тогда данные придётся дополнительно конвертировать в формат понимаемый PostgreSQL - csv или tsv, и использовать copy ... from stdin (format csv).

Нюанс: copy ... from stdin binary , binary обязывает использовать одинаковые типы данных, нельзя будет integer колонку перенести в колонку smallint, если такое требуется, то параметр binary надо опустить.

Весь код тут. И ещё немного кода для вдохновения.

@sqlhub

BY Data Science. SQL hub




Share with your friend now:
tg-me.com/sqlhub/1868

View MORE
Open in Telegram


Data Science SQL hub Telegram | DID YOU KNOW?

Date: |

Telegram Auto-Delete Messages in Any Chat

Some messages aren’t supposed to last forever. There are some Telegram groups and conversations where it’s best if messages are automatically deleted in a day or a week. Here’s how to auto-delete messages in any Telegram chat. You can enable the auto-delete feature on a per-chat basis. It works for both one-on-one conversations and group chats. Previously, you needed to use the Secret Chat feature to automatically delete messages after a set time. At the time of writing, you can choose to automatically delete messages after a day or a week. Telegram starts the timer once they are sent, not after they are read. This won’t affect the messages that were sent before enabling the feature.

For some time, Mr. Durov and a few dozen staffers had no fixed headquarters, but rather traveled the world, setting up shop in one city after another, he told the Journal in 2016. The company now has its operational base in Dubai, though it says it doesn’t keep servers there.Mr. Durov maintains a yearslong friendship from his VK days with actor and tech investor Jared Leto, with whom he shares an ascetic lifestyle that eschews meat and alcohol.

Data Science SQL hub from it


Telegram Data Science. SQL hub
FROM USA